<template>
  <div class="app-container">
    <!-- v-hasPermi="['api:mpManage:getMpUserList']" -->
    <Form v-model:formData="searchInfo" :formItems="formItems">
      <template #footer>
        <div style="text-align: left">
          <el-button size="small" icon="Search" type="primary" @click="handleQuery">搜素</el-button>
          <el-button size="small" icon="Refresh" @click="resetQuery">重置</el-button>
        </div>
      </template>
    </Form>
    <h3></h3>
    <x-table v-loading="tableLoading" :tableData="info.items" :propList="propList" @sort-change="sortChange">
      <template #headimgurl="{ row }">
        <el-image style="width: 50px; height: 50px" :src="row.headimgurl"
          :preview-src-list="[row.headimgurl]"></el-image>
      </template>
      <template #subscribe="{ row }">
        <el-tag v-if="row.subscribe == 1" type="success" effect="dark">
          已关注
        </el-tag>
        <el-tag v-else type="danger" effect="dark"> 未关注 </el-tag>
      </template>
      <template #sex="{ row }">
        <span v-if="row.sex == 1"> 男 </span>
        <span v-if="row.sex == 2"> 女 </span>
        <span v-if="row.sex == 0"> 未知 </span>
      </template>
      <template #is_admin="{ row }">
        <el-tag v-if="row.is_admin == 1" type="success"> 是 </el-tag>
        <el-tag v-else type="info"> 否 </el-tag>
      </template>
      <template #parent="{ row }">
        <span v-if="row.parent">
          {{ row.parent.nickname }}
          ({{ row.parent.id }})
        </span>
      </template>
      <template #created_time="{ row }">
        <span> {{ row.created_time }}<br />{{ row.updated_time }} </span>
      </template>

      <template #code_mode="{ row }">
        <el-tag v-if="row.code_mode == 2" type="success"> 永久 </el-tag>
        <el-tag v-else-if="row.code_mode == 1" type="info">
          临期({{
            formatDate((row.wx_code_url_create_at + row.expires_time) * 1000)
          }}过期)
        </el-tag>
        <el-tag v-else type="info">无</el-tag>
      </template>

      <template #op="{ row }">
        <el-button v-hasPermi="['api:mpUser:detail']" style="margin-right: 10px" size="small" type="primary" link
          icon="View" @click="balanceDetail({ ...row })">查看余额明细</el-button>
        <el-button v-hasPermi="['api:mpUser:detail']" style="margin-right: 10px" size="small" type="primary" link
          icon="Edit" @click="fensCommission({ ...row })">单独设置佣金</el-button>
        <!-- <el-button
            v-hasPermi="['member:mpUser:detail']"
            :loading="row.isGetDetailIng"
            style="margin-right: 10px"
            size="small"
            type="primary"
            link
            icon="View"
            @click="detail({ ...row })"
            >查看详情</el-button
          > -->
        <!-- <el-button
            v-hasPermi="['api:mpUser:clearPosterCache']"
            style="margin-right: 10px"
            size="small"
            type="primary"
            link
            icon="Edit"
            @click="clearPosterCache({ ...row })"
            >清除海报缓存</el-button
          > -->
        <!-- <el-button v-hasPermi="['api:mpUser:canelBlack']" style="margin-right: 10px" size="small" type="primary" link
          icon="Edit" @click="changePid({ ...row })">修改上级</el-button> -->
        <el-button v-hasPermi="['api:mpUser:changeMoney']" style="margin-right: 10px" size="small" type="primary" link
          icon="Edit" @click="changeMoney({ ...row })">加扣款</el-button>
        <el-button v-hasPermi="['api:mpUser:addBlack']" style="margin-right: 10px" size="small" type="primary" link
          icon="Edit" @click="addBlack({ ...row })" v-if="!row.black">拉黑</el-button>
        <el-button v-hasPermi="['api:mpUser:canelBlack']" v-if="row.black" style="margin-right: 10px" size="small"
          type="primary" link icon="Edit" @click="canelBlack({ ...row })">取消拉黑</el-button>

        <!-- <el-button
            v-hasPermi="['api:mpUser:setAdmin']"
            style="margin-right: 10px"
            size="small"
            type="primary"
            link
            icon="Avatar"
            @click="setAdmin({ ...row })"
            >设为管理员</el-button
          > -->
        <!-- v-hasPermi="['api:mpManage:getMpUserDetail']" -->
      </template>
    </x-table>
    <pagination v-if="info.total > 0" v-model:total="info.total" v-model:page="searchInfo.pageNum"
      v-model:limit="searchInfo.pageSize" @pagination="getInfo" />
    <el-dialog v-model="isShowDetail" title="用户详情">
      <el-form>
        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item :label-width="labelWidth" label="头像:">
              <el-image :src="baseInfo.headimgurl" style="width: 120px; height: 120px"
                :preview-src-list="[baseInfo.headimgurl]">
              </el-image>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label-width="labelWidth" label="昵称:">
              <span>{{ baseInfo.nickname }}</span>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <!-- <el-col :span="12">
              <el-form-item :label-width="labelWidth" label="是否关注:">
                <span>{{ baseInfo.subscribe == 1 ? "是" : "否" }}</span>
              </el-form-item>
            </el-col> -->
          <el-col :span="12">
            <el-form-item :label-width="labelWidth" label="unionid:">
              <span>{{ baseInfo.unionid }}</span>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item :label-width="labelWidth" label="关注渠道:">
              <span>{{ getSubscribe(baseInfo.subscribe_scene) }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="baseInfo.subscribe_time">
            <el-form-item :label-width="labelWidth" label="关注时间:">
              <span>{{ formatDate(baseInfo.subscribe_time * 1000) }}</span>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- <el-row :gutter="10">
            <el-col :span="12">
              <el-form-item :label-width="labelWidth" label="性别:">
                <span>{{ baseInfo.sex }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item :label-width="labelWidth" label="国家:">
                <span>{{ baseInfo.country }}</span>
              </el-form-item>
            </el-col>
          </el-row> -->
        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item :label-width="labelWidth" label="省份:">
              <span>{{ baseInfo.province }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label-width="labelWidth" label="城市:">
              <span>{{ baseInfo.city }}</span>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item :label-width="labelWidth" label="备注:">
              <span>{{ baseInfo.remark }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label-width="labelWidth" label="标签:">
              <span v-if="baseInfo.tagid_list">{{
                baseInfo.tagid_list.join(",")
              }}</span>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-dialog>
    <el-dialog v-model="isShowCommission" title="粉丝佣金" append-to-body :close-on-click-modal="false"
      :close-on-press-escape="false" width="30%">
      <el-form>
        <el-form-item :label-width="labelWidth" label="昵称">
          <span>{{ curInfo.nickname }}</span>
        </el-form-item>
        <el-form-item :label-width="labelWidth" label="当前余额">
          <span>{{ curInfo.balance }}</span>
        </el-form-item>

        <transition-group name="list" tag="div">


          <div v-for="item in (fensCommissionInfo.list)" :key="item.id"
            style="display: flex;margin: 30px auto;justify-content: center;">
            <span>
              产品：<b>{{ item.spec?.cate?.name + item.spec?.face_value }}</b>:
            </span>
            <span style="margin-left:30px;">佣金：<b>{{ item.name }}</b></span>
            <el-button style="margin-left: 30px" size="small" type="primary" link icon="Edit"
              @click="delUserCommission(item)">取消设置</el-button>
          </div>
        </transition-group>

        <el-form-item :label-width="labelWidth" label="产品">
          <el-select filterable v-model="fensCommissionInfo.spec_id">
            <el-option v-for="item in productList" :key="item.id" :label="item.cate?.name + item.face_value"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label-width="labelWidth" label="佣金">
          <el-select v-model="fensCommissionInfo.commission_id">
            <el-option v-for="item in commissionList" :key="item.id" :label="item.name" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>

      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFensCom">确 定</el-button>
          <el-button @click="isShowCommission = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog v-model="isShowChangeMoney" title="加扣款" append-to-body :close-on-click-modal="false"
      :close-on-press-escape="false" width="30%">
      <el-form>
        <el-form-item :label-width="labelWidth" label="昵称">
          <span>{{ curInfo.nickname }}</span>
        </el-form-item>
        <el-form-item :label-width="labelWidth" label="当前余额">
          <span>{{ curInfo.balance }}</span>
        </el-form-item>
        <el-form-item :label-width="labelWidth" label="修改金额">
          <el-input placeholder="请输入修改金额,负数为扣款" v-model="changeMoneyVal"></el-input>
        </el-form-item>
        <el-form-item :label-width="labelWidth" label="备注">
          <el-input placeholder="请输入备注" v-model="remark" type="textarea"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitChangeMoney">确 定</el-button>
          <el-button @click="isShowChangeMoney = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- <el-dialog v-model="isShowUser" title="设置上级" :close-on-click-modal="false" :close-on-press-escape="false"
      width="60%">

      <el-form>
        <el-form-item :label-width="labelWidth" label="昵称">
          <el-input placeholder="请输入要粉丝昵称"></el-input>
        </el-form-item>
        <el-form-item :label-width="labelWidth" label="粉丝ID">
          <el-input placeholder="请输入粉丝ID"></el-input>
        </el-form-item>
      </el-form>
      <x-table v-loading="tableLoading" :tableData="" :propList="propList" @sort-change="sortChange">
        <template #headimgurl="{ row }">
          <el-image style="width: 50px; height: 50px" :src="row.headimgurl"
            :preview-src-list="[row.headimgurl]"></el-image>
        </template>
        <template #subscribe="{ row }">
          <el-tag v-if="row.subscribe == 1" type="success" effect="dark">
            已关注
          </el-tag>
          <el-tag v-else type="danger" effect="dark"> 未关注 </el-tag>
        </template>
        <template #sex="{ row }">
          <span v-if="row.sex == 1"> 男 </span>
          <span v-if="row.sex == 2"> 女 </span>
          <span v-if="row.sex == 0"> 未知 </span>
        </template>
        <template #is_admin="{ row }">
          <el-tag v-if="row.is_admin == 1" type="success"> 是 </el-tag>
          <el-tag v-else type="info"> 否 </el-tag>
        </template>
        <template #parent="{ row }">
          <span v-if="row.parent">
            {{ row.parent.nickname }}
            ({{ row.parent.id }})
          </span>
        </template>
        <template #created_time="{ row }">
          <span> {{ row.created_time }}<br />{{ row.updated_time }} </span>
        </template>

        <template #code_mode="{ row }">
          <el-tag v-if="row.code_mode == 2" type="success"> 永久 </el-tag>
          <el-tag v-else-if="row.code_mode == 1" type="info">
            临期({{
              formatDate((row.wx_code_url_create_at + row.expires_time) * 1000)
            }}过期)
          </el-tag>
          <el-tag v-else type="info">无</el-tag>
        </template>

        <template #op="{ row }">
          <el-button v-hasPermi="['api:mpUser:detail']" style="margin-right: 10px" size="small" type="primary" link
            icon="View" @click="balanceDetail({ ...row })">查看余额明细</el-button>
          <el-button v-hasPermi="['api:mpUser:detail']" style="margin-right: 10px" size="small" type="primary" link
            icon="Edit" @click="fensCommission({ ...row })">单独设置佣金</el-button>
        </template>
      </x-table>

    </el-dialog> -->
  </div>
</template>

<script>
import {
  getList,
  // getBalanceLog as  detail,
  // setAdmin,
  changeMoney,
  canelBlack,
  addBlack,
  setFensCommission,
  getUserCommission,
  delUserCommission
  // clearPosterCache,
} from "@/api/platform/mpUser";
import { getAllList as getCommissionAllList } from "@/api/platform/commissionRule";

import { getProductList } from "@/api/platform/czProductCate"

import { formatDate } from "@/utils/index";

import _ from "lodash";
export default {
  name: "platformfensListindex",
  data() {
    return {
      productList: [],
      isShowCommission: false,
      formItems: [
        {
          prop: "id",
          label: "粉丝ID",
          placeholder: "请输入",
          lg: 6,
          type: "input",
          otherOptions: {},
        },
        {
          prop: "nickname",
          label: "昵称",
          placeholder: "请输入",
          lg: 6,
          type: "input",
          otherOptions: {},
        },
        {
          prop: "p_nickname",
          label: "上级昵称",
          placeholder: "请输入",
          lg: 6,
          type: "input",
          otherOptions: {},

        },
        {
          prop: "pid",
          label: "上级ID",
          placeholder: "请输入",
          lg: 6,
          type: "input",
          otherOptions: {},
        },
        // {
        //   prop: "subscribe",
        //   label: "是否关注",
        //   placeholder: "请选择",
        //   lg: 6,
        //   type: "select",
        //   labelWidth: "120px",
        //   options: [
        //     {
        //       key: 1,
        //       value: "是",
        //     },
        //     {
        //       key: 0,
        //       value: "否",
        //     },
        //   ],
        //   otherOptions: {},
        // },
        // {
        //   prop: "is_admin",
        //   label: "是否为管理员",
        //   placeholder: "是否为管理员",
        //   lg: 6,
        //   type: "select",
        //   labelWidth: "120px",
        //   options: [
        //     {
        //       key: 1,
        //       value: "是",
        //     },
        //   ],
        //   otherOptions: {},
        // },
        {
          prop: "unionid",
          label: "unionid",
          placeholder: "请输入",
          lg: 6,
          type: "input",
          otherOptions: {},
        },
        {
          prop: "created_time",
          label: "创建时间",
          lg: 10,
          type: "datetimerange",
          valueFormat: "x",
          otherOptions: {
            defaultTime: [
              new Date(2000, 1, 1, 0, 0, 0),
              new Date(2000, 1, 1, 23, 59, 59),
            ],
          },
        },
      ],
      labelWidth: "88px",
      tableLoading: false,
      info: {},
      searchInfo: {
        pageNum: 1,
        pageSize: 10,
      },
      propList: [
        {
          label: "粉丝ID",
          prop: "id",
        },
        {
          label: "昵称",
          prop: "nickname",
        },
        {
          label: "头像",
          prop: "headimgurl",
          slotName: "headimgurl",
        },
        // {
        //   label: "appId",
        //   prop: "appid",
        // },
        {
          label: "unionid",
          prop: "unionid",
          width: "180",
          showOverflowTooltip: false,
        },
        {
          label: "余额",
          prop: "balance",
          sortable: "custom",
          width: "150",
        },
        // {
        //   label: "是否关注",
        //   slotName: "subscribe",
        //   width: "150",
        // },
        {
          label: "上级",
          prop: "parent.nickname",
          slotName: "parent",
        },
        // {
        //   label: "海报二维码类型",
        //   prop: "code_mode",
        //   slotName: "code_mode",
        // },

        // {
        //   label: "上上级",
        //   prop: "p_parent.nickname",
        // },
        // {
        //   label: "是否为管理员",
        //   prop: "is_admin",
        //   slotName: "is_admin",
        //   width: "120",
        // },
        // {
        //   label: "标签",
        //   prop: "tagid_list",
        //   slotName: "tagid_list",
        // },
        // {
        //   label: "备注",
        //   prop: "remark",
        // },
        {
          label: "创建/修改时间",
          prop: "created_time",
          slotName: "created_time",
        },
        // {
        //   label: "创建时间",
        //   prop: "created_time",
        // },
        {
          label: "操作",
          slotName: "op",
          fixed: "right",
          showOverflowTooltip: false,
        },
      ],
      isShowDetail: false,
      labelWidth: "100px",
      baseInfo: {},
      isShowChangeMoney: false,
      curInfo: {},
      changeMoneyVal: null,
      remark: "",
      commissionList: [],
      fensCommissionInfo: {
        commission_id: null,
        spec_id: null,
        list: []
      }
    };
  },
  computed: {},
  created() {
    this.init();
  },
  mounted() { },
  methods: {
    init() {
      this.getInfo();
      this.getCommissionAllList()
      this.getProductList()
    },

    async getProductList() {
      const { data } = await getProductList();
      // channelList.push(...data);
      // 对数据扁平化
      this.productList = data;
      // this.dialogConfig.formConfig.formItems.forEach((item) => {
      //   if (item.prop == "commission_id") {
      //     item.options = data;
      //   }
      // });
    },
    async getCommissionAllList() {
      const { data } = await getCommissionAllList();
      // channelList.push(...data);
      this.commissionList = data;
      // this.dialogConfig.formConfig.formItems.forEach((item) => {
      //   if (item.prop == "commission_id") {
      //     item.options = data;
      //   }
      // });
    },
    async getInfo() {
      this.tableLoading = true;
      const params = { ...this.searchInfo };
      const { data } = await getList(params);
      this.info = data;
      this.tableLoading = false;
    },
    formatDate(val) {
      return formatDate(val);
    },
    async submitChangeMoney() {
      if (!this.changeMoneyVal) {
        this.$message.error("请输入要修改的金额");
        return false;
      }
      const params = {
        id: this.curInfo.id,
        money: this.changeMoneyVal,
        remark: this.remark,
      };
      await changeMoney(params);
      this.$message.success("修改成功");
      this.getInfo();
      this.isShowChangeMoney = false;
    },
    sortChange(e) {
      console.log(e);
      this.searchInfo.prop = e.prop;
      if (e.order == "descending") {
        this.searchInfo.order = "desc";
      }
      if (e.order == "ascending") {
        this.searchInfo.order = "asc";
      }

      this.getInfo();
    },
    changePid(item) {

    },
    addBlack(item) {
      this.$confirm(
        "拉黑将无法下单，确定要拉黑吗？",
        "提示",
        {
          cancelButtonText: "取消",
          confirmButtonText: "确定",
          type: "warning",
        }
      )
        .then(async () => {
          await addBlack(item.id);
          this.getInfo();
          this.$message({
            type: "success",
            message: "操作成功!",
          });
        })
        .catch(() => { });
    },
    fensCommission(item) {
      // 获取设置的
      getUserCommission(item.id).then((res) => {
        this.curInfo = item;
        this.fensCommissionInfo.list = res.data
        this.isShowCommission = true
      });
    },
    delUserCommission(item) {
      this.$confirm(
        "确定要取消（" + item.spec?.cate?.name + item.spec?.face_value + "）的佣金吗?",
        "提示",
        {
          cancelButtonText: "取消",
          confirmButtonText: "确定",
          type: "warning",
        }
      )
        .then(async () => {
          await delUserCommission(item.id);
          getUserCommission(item.mp_user_id).then((res) => {
            // this.curInfo = item;
            this.fensCommissionInfo.list = res.data
            // this.isShowCommission = true
            this.$message({
              type: "success",
              message: "操作成功!",
            });
          });

        })
        .catch(() => { });
    },
    canelBlack(item) {
      this.$confirm(
        "确定要取消拉黑吗?",
        "提示",
        {
          cancelButtonText: "取消",
          confirmButtonText: "确定",
          type: "warning",
        }
      )
        .then(async () => {
          await canelBlack(item.id);
          this.getInfo();
          this.$message({
            type: "success",
            message: "操作成功!",
          });
        })
        .catch(() => { });
    },
    //加减款
    changeMoney(item) {
      this.curInfo = item;
      this.isShowChangeMoney = true;
      this.changeMoneyVal = null;
      this.remark = null;
    },
    getSubscribe(sence) {
      const map = {
        ADD_SCENE_SEARCH: "公众号搜索",
        ADD_SCENE_ACCOUNT_MIGRATION: "公众号迁移",
        ADD_SCENE_PROFILE_CARD: "名片分享",
        ADD_SCENE_QR_CODE: "扫描二维码",
        ADD_SCENE_PROFILE_LINK: "图文页内名称点击",
        ADD_SCENE_PROFILE_ITEM: "图文页右上角菜单",
        ADD_SCENE_PAID: "支付后关注",
        ADD_SCENE_WECHAT_ADVERTISEMENT: "微信广告",
        ADD_SCENE_OTHERS: "其他",
      };
      return map[sence];
    },
    async submitFensCom() {
      if (!this.fensCommissionInfo.commission_id) {
        this.$message.error("请选择佣金规则")
        return false
      }
      if (!this.fensCommissionInfo.spec_id) {
        this.$message.error("请选择产品")
        return false
      }
      this.fensCommissionInfo.mp_user_id = this.curInfo.id;
      await setFensCommission(this.fensCommissionInfo)
      this.$message.success("设置成功")
      this.fensCommissionInfo.spec_id = ""
      this.fensCommissionInfo.commission_id = ""

      getUserCommission(this.fensCommissionInfo.mp_user_id).then((res) => {
        // this.curInfo = item;
        this.fensCommissionInfo.list = res.data
      });
      // this.isShowCommission = false;
    },
    balanceDetail(item) {
      // console.log(item.id);
      this.$router.push({ name: "platformuserBalanceLogindex", query: { id: item.id } });
    },
    clearPosterCache(item) {
      this.$confirm(
        "清除缓存后，如果用户海报二维码类型为永久，则不会删除，临期的将会删除，该功能用于更新海报中的头像和昵称，例如:海报中未显示头像和昵称的清除后再次获取即可！",
        "提示",
        {
          cancelButtonText: "取消",
          confirmButtonText: "确定",
          type: "warning",
        }
      )
        .then(async () => {
          await clearPosterCache(item.id);
          this.getInfo();
          this.$message({
            type: "success",
            message: "操作成功!",
          });
        })
        .catch(() => { });
    },
    setAdmin(item) {
      this.$confirm(
        "设置管理员后，平台通知类模版消息将发送至此微信,请确保设置正确，否则将被认定为骚扰,确定要设置【" +
        item.nickname +
        "】为管理员吗?",
        "提示",
        {
          cancelButtonText: "取消",
          confirmButtonText: "确定",
          type: "warning",
        }
      )
        .then(async () => {
          await setAdmin(item.id);
          this.getInfo();
          this.$message({
            type: "success",
            message: "操作成功!",
          });
        })
        .catch(() => { });
    },
    async del(item) {
      // await del(item.id);
      // this.$message.success("删除成功");
      // this.getInfo();
    },
    async detail(item) {
      console.log(`item`, item);
      // item.isGetDetailIng = true;
      //   this.$set(item, "isGetDetailIng", true);
      this.isGetDetailIng = true;
      try {
        const { data } = await detail(item.id);
        if (typeof item.tagid_list == "string") {
          item.tagid_list = JSON.parse(item.tagid_list);
        }
        this.baseInfo = item;
        this.baseInfo.subscribe_time = data.subscribe_time;
        this.baseInfo.subscribe = data.subscribe;
        this.baseInfo.subscribe_scene = data.subscribe_scene;
        console.log(this.baseInfo);
        this.isShowDetail = true;
      } finally {
        item.isGetDetailIng = false;
      }
    },
    resetQuery() {
      this.searchInfo = this.$options.data().searchInfo;
      this.getInfo();
    },
    handleQuery() {
      this.searchInfo.page = 1;
      this.getInfo();
    },
  },
};
</script>

<style lang="scss" scoped>
.list-enter-active,
.list-leave-active {
  transition: opacity 0.5s, transform 0.5s;
}

.list-enter,
.list-leave-to

/* .list-leave-active in <2.1.8 */
  {
  opacity: 0;
  transform: translateY(40px);
}
</style>